﻿using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.DbEntity.sys;
using Entity.FrameEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Tools;

namespace SysFramework
{
    public class PowerManagement:PubMethod
    {
        ReturnResult rsl;
        Commands cmd;
        OperateModel oper;
        List<OperateModel> operList;

        public PowerManagement()
        {
            rsl = new ReturnResult();
            cmd = new Commands();
        }

        /// <summary>
        /// 获取用户权限
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="menuCode"></param>
        /// <returns></returns>
        public ReturnResult GetUserPower(string userCode, string menuCode,JObject loginUser=null)
        {
            rsl = new ReturnResult();
            try
            {
                string isAdmin = "", roleCode = "";
                StringBuilder sb = new StringBuilder();
                #region 人员身份信息
                if (string.IsNullOrWhiteSpace(userCode))
                {//获取登录人员权限信息
                    userCode = loginUser["userCode"].ToString();
                    isAdmin = loginUser["isAdmin"].ToString();
                    roleCode = loginUser["powerRole"].ToString();
                }
                else
                {
                    #region 根据人员账号获取权限相关信息
                    sb.Append("select top 1 isAdmin,powerRole from sys_users_info ");
                    sb.Append("where userCode='" + userCode + "'");
                    var table = cmd.GetDataTable(sb.ToString());
                    if (table.Rows.Count <1)
                    {
                        rsl.Result = false;
                        rsl.Message = "没有获取人员:" + userCode + "的信息";
                        return rsl;
                    }
                    isAdmin = table.Rows[0]["isAdmin"].ToString();
                    roleCode = table.Rows[0]["powerRole"].ToString();
                    #endregion
                }
                #endregion

                sb.Clear();

                if (string.IsNullOrWhiteSpace(menuCode))
                {
                    rsl.Message = "菜单编码不能为空";
                    rsl.Result = false;
                    return rsl;
                }

                #region 页面标准权限0000000000修改
                string webPowers = "";
                sb.Append("select * from sys_PowerConfig_web where menuCode='" + menuCode + "' ");
                var wpTable = cmd.GetDataTable(sb.ToString());
                foreach (DataRow r in wpTable.Rows)
                {
                    webPowers += String.Format("{0},", r["pCode"].ToString());
                }
                webPowers = webPowers.TrimEnd(',');
                #endregion

                string userPower = "";
                if (isAdmin != "1")
                {
                    #region 非管理员获取菜单的全部权限
                    sb.Clear();
                    sb.Append("select top 1 isnull(operates,'') from sys_powerConfig_groupPower where ");
                    sb.Append(" groupCode='" + roleCode + "' and menuCode='" + menuCode + "'");
                    var table = cmd.GetDataTable(sb.ToString());
                    rsl.Result = true;
                    if (table.Rows.Count > 0 && string.IsNullOrWhiteSpace(table.Rows[0][0].ToString()))
                    {
                        userPower = table.Rows[0][0].ToString().Trim();
                    }
                    #endregion
                }
                else
                {//管理员权限
                    userPower = webPowers;
                }
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic["webPower"] = webPowers;//页面标准权限
                dic["userPower"] = userPower;//人员权限
                rsl.Data = dic;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 权限角色列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getPowerRoleList(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = AppSettingHelper.ReadAppSettings("PageSize");
                }
                StringBuilder sb = new StringBuilder();
                sb.Append(" isdel=0  ");
                sb = CreateSelectCondition(sb, condition);
                var list = cmd.PageList("V_powerRole_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 权限角色添加
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult UpdatePowerRole(string datas,string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                var role = JsonConvert.DeserializeObject<DbPowerRole>(datas);
                oper = new OperateModel();
                if (role.id == null || role.id == 0)
                {
                    role.isDel = 0;
                    role.createtime = getNow();
                    role.createuser = userCode;
                    role.groupCode = "R" + getTimeString();
                    role.status = "Y";
                    oper.Types = OperateModel.OperateType.Add;
                }
                else
                {
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                }
                oper.Data = role;
                operList = new List<OperateModel>();
                operList.Add(oper);
                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 根据id获取权限角色信息
        /// </summary>
        /// <param name="dataId"></param>
        /// <returns></returns>
        public ReturnResult getRoleById(string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from sys_powerConfig_groups where id=" + dataId);
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        #region LayUiTree代码
        /// <summary>
        /// layui树结构
        /// </summary>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult layUiTree(string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from sys_MenuInfo ");
                sb.Append(" where status='Y' and isdel=0 ");
                var table = cmd.GetDataTable(sb.ToString());//获取菜单全部信息
                //table.Columns.Add("operate");
                //foreach (DataRow r in table.Rows)
                //{
                //    sb.Clear();
                //    sb.Append("select * from sys_PowerConfig_web where menuCode='"+ r["menuCode"].ToString() +"'");
                //    var pTable = cmd.GetDataTable(sb.ToString());
                //    string powers = "";
                //    foreach (DataRow pr in pTable.Rows)
                //    {
                //        powers += string.Format("{0},", pr["pCode"]);
                //    }
                //    r.BeginEdit();
                //    r["operate"] = powers.TrimEnd(',');
                //    r.EndEdit();
                //}
                rsl.Data = LayUiList(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 创建导航数据
        /// </summary>
        /// <param name="table">数据源</param>
        /// <returns></returns>
        private List<Dictionary<string, object>> LayUiList(DataTable table)
        {
            List<Dictionary<string, object>> menuList = new List<Dictionary<string, object>>();
            #region 构建数据
            var fMenu = table.Select("menuLevel=1 and mType='pc'").OrderBy(x => x["orderNum"]).CopyToDataTable();//获取所有父级菜单
            for (int i = 0; i < fMenu.Rows.Count; i++)
            {
                var fdic = new Dictionary<string, object>();
                fdic["title"] = fMenu.Rows[i]["menuName"].ToString();
                fdic["id"] = fMenu.Rows[i]["menuCode"].ToString();

                #region 子菜单
                List<Dictionary<string, object>> cList = new List<Dictionary<string, object>>();
                this.LayChildUrl(table, fMenu.Rows[i]["menuCode"].ToString(), fMenu.Rows[i]["menuName"].ToString(), ref cList);
                fdic["children"] = cList;
                #endregion
                menuList.Add(fdic);
            }
            var mdic = new Dictionary<string, object>();
            mdic["title"] = "移动端权限";
            mdic["id"] = "ydapp";
            StringBuilder sb = new StringBuilder();
            var mpDr = table.Select("mType='APP' and menuLevel='1'");
            List<Dictionary<string, object>> apList = new List<Dictionary<string, object>>();
            if (mpDr.Length > 0)
            {
                Dictionary<string, object> adic;
                foreach (DataRow r in mpDr)
                {
                    adic = new Dictionary<string, object>();
                    adic["title"] = r["menuName"].ToString();
                    adic["id"] = r["menuCode"].ToString();
                    #region 子菜单
                    List<Dictionary<string, object>> cList = new List<Dictionary<string, object>>();
                    this.LayChildUrl(table, r["menuCode"].ToString(), r["menuCode"].ToString(), ref cList);
                    adic["children"] = cList;
                    #endregion
                    apList.Add(adic);
                }
            }

            mdic["children"] = apList;

            menuList.Add(mdic);
            #endregion
            return menuList;
        }
        /// <summary>
        /// 子菜单生成方法(递归)
        /// </summary>
        /// <param name="table"></param>
        /// <param name="menuCode"></param>
        /// <param name="menuName"></param>
        /// <param name="icon"></param>
        /// <param name="chlist"></param>
        private void LayChildUrl(DataTable table, string menuCode, string menuName, ref List<Dictionary<string, object>> chlist)
        {
            var dr = table.Select("parentMenu='" + menuCode + "'");
            if (dr.Length > 0)
            {
                var cMenus = dr.OrderBy(x => x["orderNum"]).CopyToDataTable();
                for (int x = 0; x < cMenus.Rows.Count; x++)
                {
                    List<Dictionary<string, object>> tempList = new List<Dictionary<string, object>>();
                    var cdic = new Dictionary<string, object>();
                    cdic["title"] = cMenus.Rows[x]["menuName"].ToString();
                    cdic["id"] = cMenus.Rows[x]["menuCode"].ToString();
                    LayChildUrl(table, cMenus.Rows[x]["menuCode"].ToString(), cMenus.Rows[x]["menuName"].ToString(), ref tempList);
                    cdic["children"] = tempList;
                    chlist.Add(cdic);
                }
            }
        }
        #endregion
     
        /// <summary>
        /// 删除权限角色
        /// </summary>
        /// <param name="dataId">数据id</param>
        /// <returns></returns>
        public ReturnResult DelRolePowers(int dataId,string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                oper = new OperateModel();
                DbPowerRole p = new DbPowerRole();
                p.id = dataId;
                p.isDel = 1;
                p.delDate = DateTime.Now.ToString("yyyy-MM-dd");
                p.delUser = userCode;
                p.status = "N";
                oper.Types = OperateModel.OperateType.Edit;
                oper.Data = p;
                oper.Conditions = "id";
                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 系统权限更新方法
        /// </summary>
        /// <param name="datas"></param>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult UpdatePowers(string datas, string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                var power = JsonConvert.DeserializeObject<DbPowers>(datas);
                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(power.pCode))
                {
                    rsl.Message = "编码不允许为空"; return rsl;
                }
                sb.Append("select id from sys_PowerConfig_powers where pCode='" + power.pCode + "'");
                var qTable = cmd.GetDataTable(sb.ToString());
                if (string.IsNullOrWhiteSpace(power.groupCode))
                {
                    power.groupCode = "0";
                }
                if (string.IsNullOrWhiteSpace(power.pName))
                {
                    power.pName = power.pCode;
                }
                power.isdel = 0;
                power.status = "Y";

                if (power.id == null || power.id == 0)
                {
                    if (qTable.Rows.Count > 0)
                    {
                        rsl.Message = "编码已存在"; return rsl;
                    }
                    power.createtime = getNow();
                    power.createuser = userCode;
                    rsl = cmd.Add(power);
                }
                else
                {
                    if (qTable.Rows.Count > 0 && qTable.Rows[0][0].ToString() != power.id.ToString())
                    {
                        rsl.Message = "编码已存在"; return rsl;
                    }
                    operList = new List<OperateModel>();
                    oper = new OperateModel();
                    oper.Data = power;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                    operList.Add(oper);

                    #region 关联数据
                    sb.Clear();
                    sb.Append("select id from sys_PowerConfig_web where pCode='"+ json["oldCode"].ToString() +"'");
                    var wpTable = cmd.GetDataTable(sb.ToString());
                    DbWebPower wp;
                    foreach (DataRow r in wpTable.Rows)
                    {
                        wp = new DbWebPower();
                        wp.id =int.Parse(r["id"].ToString());
                        wp.pCode = power.pCode;
                        oper = new OperateModel();
                        oper.Data = wp;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "id";
                        operList.Add(oper);
                    }
                    #endregion
                    rsl = cmd.MoreUpdate(operList); ;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取系统权限列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult GetPowersList(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = AppSettingHelper.ReadAppSettings("PageSize");
                }
                StringBuilder sb = new StringBuilder();
                sb.Append(" isdel=0  ");
                sb = CreateSelectCondition(sb, condition,"oldCode;id");
                var list = cmd.PageList("sys_PowerConfig_powers", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 页面权限
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="menuCode"></param>
        /// <param name="pageCount"></param>
        /// <returns></returns>
        public ReturnResult GetWebPowers(string pageIndex, string pageSize, string condition, ref string pageCount)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = AppSettingHelper.ReadAppSettings("PageSize");
                }
                sb.Append(" isdel=0  and status='Y' ");
                if (!string.IsNullOrWhiteSpace(json["pType"].ToString()))
                {
                    sb.Append("and pType='"+ json["pType"].ToString() + "'");
                }
                if (!string.IsNullOrWhiteSpace(json["pCode"].ToString()))
                {
                    sb.Append("and pCode like '%" + json["pCode"].ToString() + "%'");
                }
                if (!string.IsNullOrWhiteSpace(json["pName"].ToString()))
                {
                    sb.Append("and pName like '%" + json["pName"].ToString() + "%'");
                }
                var pTable = cmd.PageTable("sys_PowerConfig_powers", pageIndex, pageSize, sb.ToString(), "groupCode asc", ref pageCount);
                pTable.Columns.Add("wpName");
                pTable.Columns.Add("wpOrder");
                pTable.Columns.Add("wpEvent");
                pTable.Columns.Add("wpPower");
                pTable.Columns.Add("wpId");
                pTable.Columns.Add("wpIcon");
                sb.Clear();
                sb.Append("select id,isnull(wpName,'') wpName,isnull(wpOrder,'') wpOrder,isnull(wpEvent,'') wpEvent,pCode");
                sb.Append(",isnull(wpIcon,'') wpIcon from sys_PowerConfig_web where menuCode='" + json["menuCode"].ToString() + "'");
                var mTable = cmd.GetDataTable(sb.ToString());
                foreach (DataRow r in pTable.Rows)
                {
                    var dr = mTable.Select("pCode='" + r["pCode"].ToString() + "'");
                    string isPower = "0";
                    string wpid = "0";
                    r.BeginEdit();
                    if (dr.Length > 0)
                    {
                        #region 页面已存在权限
                        wpid = dr[0]["id"].ToString();
                        isPower = "1";
                        if (!string.IsNullOrWhiteSpace(dr[0]["wpName"].ToString()))
                        {
                            r["wpName"] = dr[0]["wpName"].ToString();
                        }
                        if (!string.IsNullOrWhiteSpace(dr[0]["wpOrder"].ToString()))
                        {
                            r["wpOrder"] = dr[0]["wpOrder"].ToString();
                        }
                        if (!string.IsNullOrWhiteSpace(dr[0]["wpEvent"].ToString()))
                        {
                            r["wpEvent"] = dr[0]["wpEvent"].ToString();
                        }
                        if (!string.IsNullOrWhiteSpace(dr[0]["wpIcon"].ToString()))
                        {
                            r["wpIcon"] = dr[0]["wpIcon"].ToString();
                        }
                        #endregion
                    }
                    r["wpId"] = wpid;
                    r["wpPower"] = isPower;
                    r.EndEdit();
                }
                rsl.Data = cmd.TableToDictionary(pTable);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 保存菜单权限系统权限
        /// </summary>
        /// <param name="menuCode">菜单名称</param>
        /// <param name="powers">权限</param>
        /// <returns></returns>
        public ReturnResult SaveMenuPower(string menuCode, string powers)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            operList = new List<OperateModel>();
            try
            {
                if (string.IsNullOrWhiteSpace(menuCode))
                {
                    rsl.Message = "页面编码丢失";
                    return rsl;
                }
                if (string.IsNullOrWhiteSpace(powers))
                {
                    rsl.Message = "权限数据丢失";
                    return rsl;
                }
                var arr = powers.Split(',');
                sb.Append("select * from sys_PowerConfig_web where menuCode='"+ menuCode + "'");
                var wpTable = cmd.GetDataTable(sb.ToString());
                sb.Clear();
                sb.Append("select * from sys_PowerConfig_powers where isdel=0 and status='Y'");
                var pTable = cmd.GetDataTable(sb.ToString());
                DbWebPower wp;
                foreach (string str in arr)
                {
                    if (!string.IsNullOrWhiteSpace(str))
                    {
                        string pName = "",pEvent="",pIcon="";
                        var dr = wpTable.Select("menuCode='" + menuCode + "' and pCode='"+ str.Trim() +"'");
                    
                        if (dr.Length<1)
                        {
                            #region 页面权限添加
                            var pdr = pTable.Select("pCode='" + str + "'");
                            if (pdr.Length > 0)
                            {
                                pName = pdr[0]["pName"].ToString();
                                pEvent = pdr[0]["pEvent"].ToString();
                                pIcon= pdr[0]["pIcon"].ToString();
                            }
                            wp = new DbWebPower();
                            wp.menuCode = menuCode;
                            wp.pCode = str;
                            wp.wpOrder = "1";
                            wp.wpName = pName;
                            wp.menuType = "web";
                            wp.wpEvent = pEvent;
                            wp.wpIcon = pIcon;
                            oper = new OperateModel();
                            oper.Data = wp;
                            oper.Types = OperateModel.OperateType.Add;
                            operList.Add(oper);
                            #endregion
                        }

                    }
                }
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
                else
                {
                    rsl.Message = "没有保存数据";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 保存页面权限
        /// </summary>
        /// <param name="dataId">数据id</param>
        /// <param name="fieldText">修改字段</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        public ReturnResult SaveSingleWebPower(string dataId,string fieldText,string value)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(dataId) || dataId == "0")
                {
                    rsl.Message = "此权限未能与该页面关联";return rsl;
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("update sys_PowerConfig_web set "+ fieldText+"='"+ value +"'");
                sb.Append(" where id="+ dataId);
                rsl = cmd.UpdateSql(sb.ToString());
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 删除页面权限
        /// </summary>
        /// <param name="dataId"></param>
        /// <returns></returns>
        public ReturnResult DelWebPower(string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("delete from  sys_PowerConfig_web where id=" + dataId);
                rsl = cmd.UpdateSql(sb.ToString());
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 清除权限角色页面所有权限
        /// </summary>
        /// <param name="groupCode"></param>
        /// <param name="menuCode"></param>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult CleanWebPower(string groupCode, string menuCode,string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(groupCode))
                {
                    rsl.Message = "权限角色不允许为空"; return rsl;
                }
                sb.Append("delete from sys_powerConfig_groupPower where ");
                sb.Append(" groupCode='" + groupCode.Trim() + "' and ");
                sb.Append("menuCode='" + menuCode + "'");
                rsl = cmd.UpdateSql(sb.ToString());
               
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 保存权限角色权限
        /// </summary>
        /// <param name="groupCode"></param>
        /// <param name="menuCode"></param>
        /// <param name="powers"></param>
        /// <returns></returns>
        public ReturnResult SaveRolePower(string groupCode, string menuCode, string powers,string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(groupCode))
                {
                    rsl.Message = "权限角色不允许为空"; return rsl;
                }
                if (string.IsNullOrWhiteSpace(powers))
                {
                    #region 权限信息为空时删除关联权限
                    sb.Append("delete from sys_powerConfig_groupPower where ");
                    sb.Append(" groupCode='" + groupCode.Trim() + "' and ");
                    sb.Append("menuCode='" + menuCode + "'");
                    rsl = cmd.UpdateSql(sb.ToString());
                    #endregion
                }
                else
                {
                    #region 添加权限
                    sb.Append("select top 1 * from sys_powerConfig_groupPower where ");
                    sb.Append(" groupCode='" + groupCode.Trim() + "' and menuCode='" + menuCode + "'");
                    var table = cmd.GetDataTable(sb.ToString());
                    bool isAdd = true;
                    if (table.Rows.Count > 1)
                    {
                        rsl.Message = "权限存在重复"; return rsl;
                    }
                    else
                    {
                        if (table.Rows.Count > 0)
                        {
                            isAdd = false;
                        }
                    }
                    #region 更新方法
                    DbRolePowers p = new DbRolePowers();
                    p.menuCode = menuCode;
                    p.operates = powers;
                    p.groupCode = groupCode;
                    if (isAdd)
                    {
                        p.createtime = DateTime.Now.ToString();
                        p.createuser = userCode;
                        rsl = cmd.Add(p);
                    }
                    else
                    {
                        OperateModel oper = new OperateModel();
                        oper.Data = p;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "groupCode,menuCode";
                        rsl = cmd.Edit(oper);
                    }
                    #endregion
                    #endregion
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取用户页面权限列表
        /// </summary>
        /// <param name="menuCode">菜单编码</param>
        /// <param name="roleCode">权限角色编码</param>
        /// <param name="isAdmin">登录人员身份(是否是管理员)</param>
        /// <returns></returns>
        private List<Dictionary<string,string>> GetUserWebPower(string menuCode,string roleCode,string isAdmin)
        {
            #region 获取指定菜单全部权限
            StringBuilder sb = new StringBuilder();
            sb.Append("select w.pCode,w.wpName,w.wpEvent,w.wpIcon,p.pType ");
            sb.Append("from sys_PowerConfig_web w inner join sys_PowerConfig_powers p on w.pCode=p.pCode");
            sb.Append(" where w.menuCode='" + menuCode + "'");
            string pCodes = "";
            if (isAdmin != "1")
            {//非管理员身份 只允许获取当前登录人所属的权限角色权限
                string sql = "select operates from sys_powerConfig_groupPower where groupCode='" + roleCode + "' and menuCode='"+ menuCode + "' ";
                var pTable = cmd.GetDataTable(sql);
                if (pTable.Rows.Count > 0)
                {
                    var pArr = pTable.Rows[0]["operates"].ToString().Split(',');
                    foreach (string s in pArr)
                    {
                        if (!string.IsNullOrWhiteSpace(s))
                        {
                            pCodes += string.Format("'{0}',", s);
                        }
                    }
                }
                pCodes = pCodes.TrimEnd(',');
            }
            if (!string.IsNullOrWhiteSpace(pCodes))
            {
                sb.Append(" and w.pCode in(" + pCodes + ")");
            }
            sb.Append(" order by wpOrder asc");
            var table = cmd.GetDataTable(sb.ToString());
            return cmd.TableToDictionary(table);
            #endregion
        }
        /// <summary>
        /// 人员页面操作权限
        /// </summary>
        /// <param name="menuCode"></param>
        /// <param name="userCode"></param>
        /// <param name="isAdmin"></param>
        /// <param name="roleCode"></param>
        /// <returns></returns>
        public ReturnResult GetUserWebOperate(string menuCode,string userCode,string isAdmin,string roleCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();

                #region 获取当前登录人信息
                if (string.IsNullOrWhiteSpace(isAdmin) || string.IsNullOrWhiteSpace(roleCode))
                {
                    sb.Append("select isAdmin,powerRole from sys_users_info where userCode='" + userCode + "'");
                    var uTable = cmd.GetDataTable(sb.ToString());
                    if (uTable.Rows.Count > 0)
                    {
                        if (uTable.Rows[0]["isAdmin"].ToString() == "1")
                        {
                            isAdmin = "1";
                        }
                        roleCode = uTable.Rows[0]["powerRole"].ToString();
                    }
                }
                #endregion

                var list = this.GetUserWebPower(menuCode,roleCode,isAdmin);
                var btnList = new List<Dictionary<string, string>>();
                var frmList = new List<Dictionary<string, string>>();
                foreach (var dic in list)
                {
                    if (dic["pType"].ToString() == "btn")
                    {
                        btnList.Add(dic);
                    }
                    else if (dic["pType"].ToString() == "frm")
                    {
                        frmList.Add(dic);
                    }
                }
                var dDic=new Dictionary<string,object>();
                dDic["btnPower"] = btnList;
                dDic["frmPower"] = frmList;
                rsl.Data = dDic;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取权限角色操作权限
        /// </summary>
        /// <param name="menuCode">目标菜单页面编码</param>
        /// <param name="roleCode">目标权限角色编码</param>
        /// <param name="userCode">登录人账号</param>
        /// <param name="isAdmin">登录人身份标识</param>
        /// <returns></returns>
        public ReturnResult GetRoleWebOperate(string menuCode, string roleCode, string userCode, string isAdmin)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                string userRole = "";//当前登录人所属角色编码
                #region 获取当前登录人的所属角色(只有在非管理员时才获取)
                if(isAdmin!="1" )
                {
                    sb.Append("select isAdmin,powerRole from sys_users_info where userCode='" + userCode + "'");
                    var uTable = cmd.GetDataTable(sb.ToString());
                    if (uTable.Rows.Count > 0)
                    {
                        if (uTable.Rows[0]["isAdmin"].ToString() == "1")
                        {
                            isAdmin = "1";
                        }
                        userRole = uTable.Rows[0]["powerRole"].ToString();
                    }
                }
                #endregion

                var list = this.GetUserWebPower(menuCode, userRole, isAdmin);//获取页面权限
                #region 目标角色已存在的权限
                sb.Clear();
                sb.Append("select operates from sys_powerConfig_groupPower where groupCode='" + roleCode +"'");
                sb.Append(" and menuCode='"+ menuCode + "'");
                var hTable=cmd.GetDataTable(sb.ToString());
                var hasPowers = "";
                if (hTable.Rows.Count > 0)
                {
                    hasPowers = hTable.Rows[0][0].ToString();
                }
                #endregion
        
                var dDic = new Dictionary<string, object>();
                dDic["webPowers"] = list;
                dDic["hasPowers"] = hasPowers;
                rsl.Data = dDic;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        public ReturnResult DelPowerByCode(string pCode,string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pCode))
                {
                    rsl.Message = "权限编码丢失";return rsl;
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("select id from sys_PowerConfig_web where pCode='"+ pCode +"'");
                var wtTable = cmd.GetDataTable(sb.ToString());
                if (wtTable.Rows.Count > 0)
                {
                    rsl.Message = "权限已被应用，不能删除"; return rsl;
                }
                DbPowers p = new DbPowers();
                p.pCode = pCode;
                p.isdel = 1;
                p.delMsg = string.Format("{0}({1})",userCode,getNow());
                oper = new OperateModel();
                oper.Data = p;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "pCode";
                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
    }
}
